﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Trirand.Web.UI.WebControls;


namespace TestJQGrid.Tax_Section
{
    public partial class TaxMaster : System.Web.UI.Page
    {
        #region load data
        protected void Page_Load(object sender, EventArgs e)
        {
            //string txt=JQGrid1.AjaxCallBackMode.ToString();
            if (!Page.IsPostBack)
            {
                fillLBState();
                fillPriority("Test", false);
                fillTax();
            }
        }

        public void fillLBState()
        {
            DataTable dt = new DataTable();
            dt = GlobalMethods.ExecuteSelectQuery("select * from ValidValues where TableName='State' order by ColumnName");

            LBStates.DataSource = dt;
            LBStates.DataBind();
        }

        public void fillTax()
        {
            DataTable dt = new DataTable();
            dt = GlobalMethods.ExecuteSelectQuery("select * from ValidValues where TableName='Taxes' order by ColumnName");
            DDTax.DataSource = dt;
            DDTax.DataBind();
        }

        public void fillPriority(string stateCode,bool isInsert)
        {
            DDPriority.Items.Clear();
            string priority="";
            
            if (isInsert)
                priority = "max(Priority)+1";
            else
                priority = "max(Priority)";

            priority = "max(Priority)+1";   // Default for Edit and Add

            int p_no = 0;

            try
            {
                p_no = Convert.ToInt32(GlobalMethods.ExecuteScalar("select " + priority + " from TaxMaster t where State ='" + stateCode + "'"));
            }
            catch (Exception ex)
            {
                p_no = 1;
            }

            for (int i = 1; i <= p_no; i++)
            {
                ListItem li = new ListItem(i.ToString(), i.ToString());
                DDPriority.Items.Add(li);
            }
        }

        protected void JQGrid1_DataRequesting(object sender, JQGridDataRequestEventArgs e)
        {
            DataTable dt = getTaxDetailsPerState();
            if (dt == null) return;

            JQGrid1.DataSource = dt;
            JQGrid1.DataBind();

            //Session["FromDate"] = Convert.ToString(dt.Compute("min(FromDate)", String.Empty));
            //Session["ToDate"] = Convert.ToString(dt.Compute("max(ToDate)", String.Empty));

            //setDate();
        }

        DataTable getTaxDetailsPerState()
        {
            if (Session["SelectedState4Tax"] == null) return null;

            string state = Session["SelectedState4Tax"].ToString();
            string query = "select * from TaxMaster where State='" + state + "' order by Priority,TaxRange desc";

            //if ((String.IsNullOrWhiteSpace(TBFrom.Text) || String.IsNullOrWhiteSpace(TBToDate.Text)))
            //{
            //    query = "select * from TaxMaster t where State='" + state + "' order by Priority";
            //}
            //else
            //{
            //    query = "select * from TaxMaster t where State='" + state + "' and t.FromDate='" + Convert.ToDateTime(TBFrom.Text) + "' AND T.ToDate='" + Convert.ToDateTime(TBToDate.Text) + "' order by Priority";
            //}           

            DataTable dt = new DataTable();
            dt = GlobalMethods.ExecuteSelectQuery(query);

            return dt;
        }

        protected void LBStates_SelectedIndexChanged(object sender, EventArgs e)
        {
            Session["SelectedState4Tax"] = LBStates.SelectedValue.ToString();
            fillPriority(LBStates.SelectedValue, true);
        }

        #endregion

        #region jqgrid operation
        protected void JQGrid1_OnRowAdding(object sender, Trirand.Web.UI.WebControls.JQGridRowAddEventArgs e)
        {
            int taxRange = 0;

            if (String.IsNullOrWhiteSpace(e.RowData["TaxRange"].ToString()))
            {
                taxRange = 0;
            }
            else
            {
                taxRange = Convert.ToInt32(e.RowData["TaxRange"].ToString());
            }

            string state = Session["SelectedState4Tax"].ToString();

           // string chkPreRecord = GlobalMethods.ExecuteScalar("select TaxType from TaxMaster where State='" + state + "' and FromDate='" + Convert.ToDateTime(e.RowData["FromDate"].ToString()) + "' and ToDate='" + Convert.ToDateTime(e.RowData["ToDate"].ToString()) + "' and TaxType='" + e.RowData["TaxType"].ToString() + "'");

          //  if (!String.IsNullOrWhiteSpace(chkPreRecord)) return;

            //string query = "select max(Priority)+1 from TaxMaster where State='" + state + "'";

            //String priority = GlobalMethods.ExecuteScalar(query);
            String priority = DDPriority.SelectedValue;
            if (String.IsNullOrWhiteSpace(priority)) priority = "1";

            string InsertQuery = "INSERT INTO TAXMASTER([State],[TaxType],[Priority],[TaxPercent],[TaxRange],[FromDate],[ToDate],[Applicable],[CreatedOn],[CreatedBy])";
            InsertQuery += " VALUES('" + Session["SelectedState4Tax"].ToString() + "'";
            InsertQuery += ",'" + e.RowData["TaxType"].ToString() + "'";
            InsertQuery += "," + priority + "";
            InsertQuery += "," + Convert.ToDecimal(e.RowData["TaxPercent"].ToString()) + "," + taxRange + ",'" + Convert.ToDateTime(e.RowData["FromDate"].ToString()) + "','" + Convert.ToDateTime(e.RowData["ToDate"].ToString()) + "','" + e.RowData["Applicable"].ToString() + "','" + DateTime.Now.ToString() + "','" + Session["loginId"].ToString() + "')";

            GlobalMethods.ExecuteNonQuery(InsertQuery);
            WebMsgBox.Show("Record added successfully.");
        }

        protected void JQGrid1_OnRowEditing(object sender, Trirand.Web.UI.WebControls.JQGridRowEditEventArgs e)
        {
            string UpdateQuery = "UPDATE TAXMASTER SET TaxType='" + e.RowData["TaxType"].ToString() + "'";
            UpdateQuery += ",Priority=" + Convert.ToInt32(e.RowData["Priority"].ToString()) + "";
            UpdateQuery += ",TaxPercent=" + Convert.ToDecimal(e.RowData["TaxPercent"].ToString()) + "";
            UpdateQuery += ",TaxRange=" + Convert.ToInt64(e.RowData["TaxRange"].ToString()) + "";
            UpdateQuery += ",FromDate='" + Convert.ToDateTime(e.RowData["FromDate"].ToString()) + "'";
            UpdateQuery += ",ToDate='" + Convert.ToDateTime(e.RowData["ToDate"].ToString()) + "'";
            UpdateQuery += ",Applicable='" + e.RowData["Applicable"].ToString() + "'";
            UpdateQuery += " WHERE EntryId=" + Convert.ToInt32(e.RowData["EntryId"].ToString()) + "";

            GlobalMethods.ExecuteNonQuery(UpdateQuery);
            WebMsgBox.Show("Record updated successfully.");
        }

        protected void JQGrid1_RowDeleting(object sender, Trirand.Web.UI.WebControls.JQGridRowDeleteEventArgs e)
        {
            GlobalMethods.ExecuteNonQuery("update TaxMaster set ToDate='" + DateTime.Now.ToString() + "' where [EntryId]=" + Convert.ToInt32(e.RowKey));
            WebMsgBox.Show("Record deleted succesfully.");
        }

        #endregion

        protected void JQGrid1_RowSelecting(object sender, JQGridRowSelectEventArgs e)
        {
            //    Session["PriorityRowID"] = e.RowKey.ToString();
            fillPriority(LBStates.SelectedValue, false);
        }

        protected void IBUp_Click(object sender, ImageClickEventArgs e)
        {
            UpDown_Priority("UP");
        }

        protected void IBDown_Click(object sender, ImageClickEventArgs e)
        {
            UpDown_Priority("DOWN");
        }

        public void UpDown_Priority(string order)
        {
            //if no selected row or no selected state then return
            string row = JQGrid1.SelectedRow.ToString();
            if (String.IsNullOrWhiteSpace(row)) return;

            //retrieve all entries per state
            DataTable dt = getTaxDetailsPerState();

            //get index of selected row
            DataRow[] dr = dt.Select("EntryId=" + row);
            int index = dt.Rows.IndexOf(dr[0]);

            //return in case seleced row is first(4UP) and last (4down)
            if (index == 0 && order.Equals("UP")) return;
            if ((index + 1) == dt.Rows.Count && order.Equals("DOWN")) return;

            //if UP then next is prevLine, else if down next is next line
            int nextIndex = index + 1;
            if (order.Equals("UP")) nextIndex = index - 1;

            string currPriority = dt.Rows[index]["Priority"].ToString();
            string nextPriority = dt.Rows[nextIndex]["Priority"].ToString();

            GlobalMethods.ExecuteNonQuery("update TaxMaster set Priority=" + nextPriority + " where EntryId=" + dt.Rows[index]["EntryId"].ToString());
            GlobalMethods.ExecuteNonQuery("update TaxMaster set Priority=" + currPriority + " where EntryId=" + dt.Rows[nextIndex]["EntryId"].ToString());
        }


        //public void setDate()
        //{
        //    if (Session["FromDate"] != null)
        //    {
        //        JQDatePicker1.CurrentText = Session["FromDate"].ToString();
        //        Trirand.Web.UI.WebControls.
        //        TBFrom.Text = Session["FromDate"].ToString();
        //    }

        //    if (Session["ToDate"] != null)
        //    {
        //        JQDatePicker2.CurrentText = Session["ToDate"].ToString();
        //        TBToDate.Text = Session["ToDate"].ToString();
        //    }
        //}
    }
}